import React, { useState, useEffect } from 'react';
import { DatePicker, Select, Spin } from 'antd';
import { CaretDownOutlined } from '@ant-design/icons';
import { priceSpreadSourceOptions, priceSpreadValueOptions } from '../../helper';
import { useSetState } from 'ahooks';
import { TjSlideSelect } from '@/tjComponents';
import moment from 'moment';
import _ from 'lodash';
import styles from './index.less';
import { connect } from 'umi';
import { TjChart } from '@/pages/ETrade/components';

const defaultHistoryData = {
  valueType: 1,
  dates: [moment().subtract(7, 'day'), moment().subtract(1, 'day')],
};

const PriceSpreadCharts = (props) => {
  const { searchForm = {}, dispatch, priceChartData = {}, priceLoading } = props;
  const [req, setReq] = useSetState({
    sourceType: null,
    dates: [moment().subtract(7, 'day'), moment().subtract(1, 'day')],
  });

  const changeSourceType = (v) => {
    let obj = {
      sourceType: v,
    };

    if (v === 'tianji') {
      obj = _.mapValues({ ...req }, () => undefined);
      obj.sourceType = v;
    }
    if (v === 'history') {
      obj = {
        ...obj,
        ...defaultHistoryData,
      };
      if (searchForm.marketId !== 'PHBSX') {
        obj.correction = 'after';
      }
    }
    setReq(obj);
  };

  const changeCorrection = (v) => {
    setReq({
      correction: v,
    });
  };

  const changeDate = (v) => {
    setReq({
      dates: v,
    });
  };

  const changeValueType = (v) => {
    setReq({
      valueType: v,
    });
  };

  const query = () => {
    if (req.sourceType === 'tianji') {
      // 获取天机预测数据
      dispatch({
        type: 'shortTermForecastingRedesignV2/getTianjiChart',
        payload: {
          endDate: searchForm.calendarDate,
          startDate: searchForm.calendarDate,
          marketId: searchForm.marketId,
          stationId: searchForm.stationId,
          calendarDate: searchForm.calendarDate,
          saveType: searchForm.saveType,
          baseValue: 0,
          correction: 'before',
          valueType: 1,
        },
      });
    } else {
      // 获取历史预测数据
      dispatch({
        type: 'shortTermForecastingRedesignV2/getHistoryChart',
        payload: {
          calendarDate: searchForm.calendarDate,
          stationId: searchForm.stationId,
          sourceType: req.sourceType,
          saveType: searchForm.saveType,
          marketId: searchForm.marketId,
          baseValue: 0, // （0无基数  1有基数）原山西省份有有无基数下拉选择，新版本已取消
          correction: 'after', //（before修正前  after修正后） 新版本已取消
          startDate: req.dates[0]?.format('YYYY-MM-DD'),
          endDate: req.dates[1]?.format('YYYY-MM-DD'),
          valueType: req.valueType,
        },
      });
    }
  };

  useEffect(() => {
    if (searchForm.marketId) {
      // 目前只有山西和山东有天机的预测数据，其他省份只有历史数据
      if (searchForm.marketId === 'PHBSX' || searchForm.marketId === 'PHBSD') {
        setReq({
          sourceType: 'tianji',
        });
      } else {
        setReq({
          sourceType: 'history',
          correction: 'after',
          ...defaultHistoryData,
        });
      }
    }
  }, [searchForm.marketId, searchForm]);

  useEffect(() => {
    if (req.sourceType) {
      query();
    }
  }, [req]);

  return (
    <Spin spinning={priceLoading}>
      <div className={styles.price_spread_charts}>
        <div className={styles.title}>
          <div className={styles.name}>
            价差-
            <Select
              options={priceSpreadSourceOptions(searchForm.marketId || 'PHBSX')}
              suffixIcon={<CaretDownOutlined />}
              bordered={false}
              value={req.sourceType}
              onChange={changeSourceType}
              className={styles.name_select}
            />
          </div>

          <div className={styles.options}>
            {req.sourceType === 'history' && (
              <>
                <Select
                  options={priceSpreadValueOptions}
                  style={{ width: 90 }}
                  value={req.valueType}
                  onChange={changeValueType}
                />
                <DatePicker.RangePicker
                  format="YYYYMMDD"
                  value={req.dates}
                  // disabledDate={disabledDate as any}
                  placeholder={['请选择', '请选择']}
                  onChange={changeDate}
                  separator={'-'}
                />
              </>
            )}

            {searchForm.marketId && searchForm.marketId !== 'PHBSX' && (
              <TjSlideSelect
                value={req.correction}
                onChange={changeCorrection}
                items={[
                  { label: '修正前', value: 'before' },
                  { label: '修正后', value: 'after' },
                ]}
              />
            )}
          </div>
        </div>
        <div className={styles.charts_box}>
          <TjChart option={priceChartData} group={'A'} />
        </div>
      </div>
    </Spin>
  );
};

export default connect(({ shortTermForecastingRedesignV2 }) => ({
  searchForm: shortTermForecastingRedesignV2.searchForm,
  priceChartData: shortTermForecastingRedesignV2.priceChartData,
  priceLoading: shortTermForecastingRedesignV2.priceLoading,
}))(PriceSpreadCharts);
